<template>
  <MyDialog
    :dialog-form="dialogForm"
    :dialog-visible="props.dialogVisible"
    @dialogClose="onClose"
    @dialogConfirm="onSubmit"
  >
    <template #dialogBox>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="130px"
        status-icon
      >
        <el-form-item label="企业简称" prop="shortName">
          <el-input
            v-model="ruleForm.shortName"
            placeholder="输入企业简称"
            maxlength="8"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="企业地址">
          <div>
            <el-select
              v-model="ruleForm.provinceId"
              class="m-2"
              style="width: 33%"
              placeholder="省"
              clearable
              @change="proChange"
            >
              <el-option
                v-for="item in allAreasList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <el-select
              v-model="ruleForm.cityId"
              class="m-2"
              style="width: 33%"
              placeholder="市"
              clearable
              @change="cityChange"
            >
              <el-option
                v-for="item in selectCityList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <el-select
              v-model="ruleForm.areaId"
              class="m-2"
              style="width: 33%"
              placeholder="区"
              clearable
              @change="areaChange"
            >
              <el-option
                v-for="item in selectAreaList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </div>
          <el-input
            v-model="ruleForm.address"
            autocomplete="off"
            style="width: 100%; margin-top: 10px"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="法定代表人">
          <el-input v-model="ruleForm.legalName" placeholder="输入法定代表人" />
        </el-form-item>
        <el-form-item label="手机号" prop="legalTel">
          <el-input v-model="ruleForm.legalTel" placeholder="输入手机号" />
        </el-form-item>
        <el-form-item label="成立日期">
          <el-date-picker
            v-model="ruleForm.establishDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择成立日期"
          />
        </el-form-item>
        <el-form-item label="企业规模">
          <el-select v-model="ruleForm.companySize" placeholder="选择企业规模">
            <el-option
              v-for="item in allCompanySize"
              :key="item.id"
              :label="item.configValue"
              :value="item.configValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属行业">
          <el-select v-model="ruleForm.tradeName" placeholder="选择所属行业">
            <el-option
              v-for="item in allTrade"
              :key="item.id"
              :label="item.configValue"
              :value="item.configValue"
            />
          </el-select>
        </el-form-item>
        <h4>企业LOGO设置</h4>
        <div class="logoSet">
          <div class="logoSet__left" v-if="ruleForm.thumbnailLogo != ''">
            <el-image
              style="width: 72px; height: 72px"
              :src="ruleForm.thumbnailLogo"
              :zoom-rate="1.2"
              :preview-src-list="srcList"
              :initial-index="1"
              fit="cover"
            />
          </div>
          <div class="logoSet__right">
            <el-upload
              :action="`${proxy.$http}/user/upload/uploadFile`"
              :auto-upload="true"
              :http-request="(resp: any) => { return handleUpload(resp, 2) }"
              :limit="1"
              v-model:file-list="fileList"
              :headers="headers"
              accept=".png,.jpg,jpeg"
              :show-file-list="false"
              :on-error="(resp: any) => { return fileError(resp, 2) }"
            >
              <el-button plain type="primary">上传图片</el-button>
            </el-upload>
            <p class="tips">提示：可上传64PX*64PX的png格式图片</p>
          </div>
        </div>
      </el-form>
    </template>
  </MyDialog>
</template>
<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  getCurrentInstance,
  defineAsyncComponent
} from 'vue'
import {
  FormInstance,
  FormRules,
  ElLoading,
  UploadUserFile,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import provinces from '/@/jsons/provinces.json'
import cities from '/@/jsons/cities.json'
import areas from '/@/jsons/areas.json'
import { dictionaryOPList, uploadFileApi } from '/@/api/publicApi'
import { updateCompanyInfo } from '/@/api/setting/enterpriseInfo'
const MyDialog = defineAsyncComponent(
  () => import('/@/components/dialog/index.vue')
)
const props = defineProps({
  dialogVisible: Boolean,
  companyInfo: Object
})
const emit = defineEmits(['closeDialog', 'submitDialog'])

watch(
  () => props.dialogVisible,
  () => {
    if (props.dialogVisible) {
      ruleForm.value.id = props.companyInfo?.id
      ruleForm.value.shortName = props.companyInfo?.shortName
      ruleForm.value.provinceId =
        props.companyInfo?.provinceId != ''
          ? JSON.stringify(props.companyInfo?.provinceId)
          : ''
      ruleForm.value.province = props.companyInfo?.province
      ruleForm.value.cityId =
        props.companyInfo?.cityId != ''
          ? JSON.stringify(props.companyInfo?.cityId)
          : ''
      ruleForm.value.city = props.companyInfo?.city
      ruleForm.value.areaId =
        props.companyInfo?.areaId != ''
          ? JSON.stringify(props.companyInfo?.areaId)
          : ''
      ruleForm.value.area = props.companyInfo?.area
      ruleForm.value.address = props.companyInfo?.address
      ruleForm.value.legalName = props.companyInfo?.legalName
      ruleForm.value.legalTel = props.companyInfo?.legalTel
      ruleForm.value.establishDate = props.companyInfo?.establishDate
      ruleForm.value.companySize = props.companyInfo?.companySize
      ruleForm.value.tradeName = props.companyInfo?.tradeName
      ruleForm.value.thumbnailLogo = props.companyInfo?.thumbnailLogo
      getCity(ruleForm.value.provinceId)
      getArea(ruleForm.value.cityId)
    }
  }
)
const { proxy } = getCurrentInstance() as any
const ruleFormRef = ref<FormInstance>()
const dialogForm = reactive({
  width: '30%',
  title: '编辑'
})

//所有地区数据
const allAreasList = ref<any>(provinces)

const ruleForm = ref({
  id: '',
  shortName: '',
  provinceId: '',
  province: '',
  cityId: '',
  city: '',
  areaId: '',
  area: '',
  address: '',
  legalName: '',
  legalTel: '',
  establishDate: '',
  companySize: '',
  tradeName: '',
  thumbnailLogo: ''
})

const validateTel2 = (rule: any, value: any, callback: any) => {
  let reg2 =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/g
  if (value && !reg2.test(value)) {
    return callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  shortName: [{ required: true, message: '输入企业简称', trigger: 'blur' }],
  legalTel: [{ validator: validateTel2, trigger: 'blur' }]
})

//地址选择
//城市下拉框内容所有值
const selectCityList = ref<any>([])

//区域下拉框内容所有值
const selectAreaList = ref<any>([])
const getCity = (val: any) => {
  selectCityList.value = []
  cities.forEach((item: any) => {
    if (item.provinceCode == val) {
      selectCityList.value.push(item)
    }
  })
}
const getArea = (val: any) => {
  selectAreaList.value = []
  areas.forEach((item: any) => {
    if (item.cityCode == ruleForm.value.cityId) {
      selectAreaList.value.push(item)
    }
  })
}
const proChange = (val: any) => {
  if (val == '') {
    selectCityList.value = []
    selectAreaList.value = []
    ruleForm.value.province = ''
    ruleForm.value.cityId = ''
    ruleForm.value.city = ''
    ruleForm.value.areaId = ''
    ruleForm.value.area = ''
  } else {
    getCity(val)
  }
  allAreasList.value.forEach((element: any) => {
    if (element.code == val) {
      ruleForm.value.province = element.name
    }
  })
}
const cityChange = (val: any) => {
  if (val == '') {
    selectAreaList.value = []
    ruleForm.value.city = ''
    ruleForm.value.areaId = ''
    ruleForm.value.area = ''
  } else {
    getArea(val)
  }
  selectCityList.value.forEach((element: any) => {
    if (element.code == val) {
      ruleForm.value.city = element.name
    }
  })
}
const areaChange = (val: any) => {
  if (val == '') {
    ruleForm.value.area = ''
  } else {
    selectAreaList.value.forEach((element: any) => {
      if (element.code == val) {
        ruleForm.value.area = element.name
      }
    })
  }
}

//获取所有行业
const allTrade = ref<any>([])
const getTrade = async () => {
  let res = await dictionaryOPList({ configType: 'trade', keyword: '' })
  if (res.code == 0) {
    allTrade.value = res.data
  }
}
getTrade()

//获取所有行业
const allCompanySize = ref<any>([])
const getCompanySize = async () => {
  let res = await dictionaryOPList({ configType: 'company_size', keyword: '' })
  if (res.code == 0) {
    allCompanySize.value = res.data
  }
}
getCompanySize()

//图片相关
let uploadLoading = ref(false)
const fileList = ref<UploadUserFile[]>([])
const srcList = ref<any>([])
const token = JSON.parse(sessionStorage.getItem('shebei') as any).token
const headers = {
  'Content-Type': 'multipart/form-data',
  'API-User-Token': token
}
const handleUpload = (file: any, type: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '上传中',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  uploadFileApi({ type: 2, file: file.file }).then((res) => {
    ruleForm.value.thumbnailLogo = res.data.fileIds[0]
    uploadLoading.value = false
    fileList.value = []
    ElMessage.success('企业LOGO上传成功！')
    loading.close()
  })
}

const fileError = (err: any, type: any) => {
  ElMessage.error('项目文件上传失败！')
  fileList.value = []
  ruleForm.value.thumbnailLogo = ''
  uploadLoading.value = false
}

const onClose = () => {
  if (!ruleFormRef.value) return
  ruleFormRef.value.resetFields()
  emit('closeDialog')
}

const onSubmit = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid: any, fields: any) => {
    if (valid) {
      //   let res = await updateCompanyInfo(ruleForm.value)
      //   if (res.code == 0) {
      emit('submitDialog', ruleForm.value)
      //   }
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>
<style scoped lang="scss">
.logoSet {
  display: flex;
  &__left {
    border-radius: 4px;
    margin-right: 24px;
    cursor: pointer;

    img {
      height: 100%;
      width: 100%;
    }
  }

  &__right {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
}
</style>
